package org.mq.mymq.nameserver.event.listener;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.enums.NameServerEventCode;
import org.mq.mymq.common.enums.NameServerResponseCode;
import org.mq.mymq.common.event.Listener;
import org.mq.mymq.nameserver.common.CommonCache;
import org.mq.mymq.nameserver.event.model.StartReplicationEvent;
import org.mq.mymq.nameserver.utils.NameserverUtil;

import java.net.InetSocketAddress;

/**
 * @ClassName StartReplicationListener
 * @Description 开启同步复制监听器
 * @Author jiarong_ye
 * @Date 2025/6/20 11:51
 * @Version 1.0
 */
public class StartReplicationListener implements Listener<StartReplicationEvent> {
    @Override
    public void onReceive(StartReplicationEvent event) throws Exception {
        boolean isVerify = NameserverUtil.isVerify(event.getUser(), event.getPassword());
        ChannelHandlerContext ctx = event.getChannelHandlerContext();
        if (!isVerify) {
            TcpMsg tcpMsg = new TcpMsg(NameServerResponseCode.ERROR_USER_OR_PASSWORD.getCode(),
                    NameServerResponseCode.ERROR_USER_OR_PASSWORD.getDesc().getBytes());
            ctx.writeAndFlush(tcpMsg);
            ctx.close();
            throw new IllegalAccessException("error account to connected!");
        }
        InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
        event.setSlaveIp(inetSocketAddress.getHostName());
        event.setSlavePort(String.valueOf(inetSocketAddress.getPort()));
        String reqId = event.getSlaveIp() + ":" + event.getSlavePort();
        ctx.attr(AttributeKey.valueOf("reqId")).set(reqId);
        CommonCache.getReplicationChannelManager().put(reqId, ctx);
        TcpMsg tcpMsg = new TcpMsg(NameServerEventCode.MASTER_START_REPLICATION_ACK.getCode(), new byte[0]);
        ctx.writeAndFlush(tcpMsg);

        // 同步给到从节点。比较严谨的同步，binlog类型，对于数据的顺序性要求很高
        // 可能是无顺序的状态
        // 把同步的数据写入一条队列，专门有一条线程从队列中提取数据同步到各个从节点

    }
}
